import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'
import { Message } from 'element-ui'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //用户数据
    user: {
      UserId: null,
      loginName:null,
      loginPwd:null,
      UserName: null,
      roleID: null,
      RoleName:null,
      DeptName:null,
      Token: null,
      Exp: null,
      sex: null,
      birthday:null,
      phone: null,
      Image: null,
      lastTime: null,
      status:null
    },
    //菜单相关
    //选中的值
    tableTabsValue: '1'
    //选项卡 数据
    , tableTabs: []
  },
  getters: {
  },
  mutations: {
    setUser(state, payload) {
      sessionStorage.setItem('user', JSON.stringify(payload));
      state.user = JSON.parse(JSON.stringify(payload));
    },
    //菜单相关
    //添加选项卡
    addTab(state, menu) {
      console.log(menu.Url);
      if(menu.Url!=""){
        //先判断当前选项卡 是否存在
        if (!state.tableTabs.some(v => v.name == menu.MenuID)) {
          state.tableTabs.push({
            title: menu.MenuName,
            name: menu.MenuID + '',
            icon: menu.Icon,
            viewUrl: menu.Url
          });
  
        }
        //切换选中
        state.tableTabsValue = menu.MenuID + '';
        //通过  tableTabsValue  当前选中选项卡获取 路由地址
        let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
        //切换路由
        if(router.currentRoute.path!=viewUrl){
          router.push(viewUrl);
        }

      } else {
        Message({
          message: '敬请期待'
        })
      }

    },
    //移除选项卡
    removeTab(state, targetName) {
      let tabs = state.tableTabs;
      let activeName = state.tableTabsValue;
      console.log(targetName);
      console.log(tabs);
      console.log(activeName);
      //移除的选项卡是当前选中选项卡
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
        //通过  tableTabsValue  当前选中选项卡获取 路由地址
        let viewUrl = state.tableTabs.filter(v => v.name == activeName)[0].viewUrl;
        console.log(viewUrl);
        //切换路由
        router.push(tabs.length == 1 ? "/" : viewUrl);
      }
      state.tableTabsValue = activeName;
      //使用筛选移除
      state.tableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    //----------------------------------------------------------------
    //点击选项卡切换
    clickTab(state) {
      //通过  tableTabsValue  当前选中选项卡获取 路由地址
      let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
      //切换路由 
      if (location.pathname != viewUrl)
        router.push(viewUrl);
    },
    edittableTabsValue(state, value) {
      state.tableTabsValue = value;
    }
  },
  actions: {
  },
  modules: {
  }
})
